class Solution(object):
    def numMagicSquaresInside(self, grid):
        m = len(grid)
        n = len(grid[0])
        if m < 3 or n < 3:
            return 0
        t = 0

        def search(i, j):
            if grid[i + 1][j + 1] == 5:
                p = [0] * 9
                for x in range(3):
                    for y in range(3):
                        if grid[i + x][j + y] > 10:
                            return 0
                        p[grid[i + x][j + y] - 1] = 1
                if all(p):
                    for x in range(3):
                        if sum([grid[i][y] for y in range(j, j + 3)]) != 15:
                            return 0
                        if sum([grid[x][j] for x in range(i, i + 3)]) != 15:
                            return 0
                    if grid[i][j] + grid[i + 2][j + 2] != 10:
                        return 0
                    if grid[i][j + 2] + grid[i + 2][j] != 10:
                        return 0
                    return 1
                else:
                    return 0
            else:
                return 0

        for i in range(m - 2):
            for j in range(n - 2):
                t += search(i, j)
        return t